package xyx.chenweb.myapp.config;

import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.ehcache.EhCacheManager;
import org.apache.shiro.realm.Realm;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.springframework.aop.framework.autoproxy.DefaultAdvisorAutoProxyCreator;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.DependsOn;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class ShiroConfig {

    //1.创建shiroFilterFactoryBean   负责拦截所有请求
    @Bean
    public ShiroFilterFactoryBean getShiroFilterFactoryBean(DefaultWebSecurityManager defaultWebSecurityManager){

        ShiroFilterFactoryBean shiroFilterFactoryBean = new ShiroFilterFactoryBean();

        shiroFilterFactoryBean.setSecurityManager(defaultWebSecurityManager);

        Map<String, String> map = new HashMap<String, String>();

        map.put("/chen/api/**", "anon");//anon 设置为公共资源 在authc前面
        map.put("/**", "authc");//所有资源均需要认证和授权

        return shiroFilterFactoryBean;
    }

    //2.创建安全管理器
    @Bean
    public DefaultWebSecurityManager getDefaultWebSecurityManager(){
        DefaultWebSecurityManager defaultWebSecurityManager = new DefaultWebSecurityManager();

        defaultWebSecurityManager.setRealm(getRealm());
        //给安全管理器设置Realm
        return defaultWebSecurityManager;
    }

    //3.创建自定义realm
    @Bean
    public Realm getRealm(){
        MyShiroRealm myShiroRealm = new MyShiroRealm();
        //修改凭证消炎匹配器
        HashedCredentialsMatcher hashedCredentialsMatcher = new HashedCredentialsMatcher();
        hashedCredentialsMatcher.setHashAlgorithmName("md5");//md5加密
        hashedCredentialsMatcher.setHashIterations(1024);//散列次数
        myShiroRealm.setCredentialsMatcher(hashedCredentialsMatcher);

        myShiroRealm.setCacheManager(new EhCacheManager());
        myShiroRealm.setCachingEnabled(true); //开启全局缓存
        myShiroRealm.setAuthenticationCachingEnabled(true);//开启认证缓存
        myShiroRealm.setAuthenticationCacheName("authenticationCache"); //认证名
        myShiroRealm.setAuthorizationCachingEnabled(true); //开启授权缓存
        myShiroRealm.setAuthenticationCacheName("authorizationCache");//授权名
        return myShiroRealm;
    }

    @Bean
    @DependsOn("lifecycleBeanPostProcessor")
    public DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator() {
        DefaultAdvisorAutoProxyCreator defaultAdvisorAutoProxyCreator = new DefaultAdvisorAutoProxyCreator();
        defaultAdvisorAutoProxyCreator.setProxyTargetClass(true);
        return defaultAdvisorAutoProxyCreator;
    }
}
